package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.entity.SetmealDish;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishService;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/setmeal")
@Api(tags = "套餐相关接口")
public class SetmealController {

    @Autowired
    private SetmealService setmealService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private SetmealDishService setmealDishService;
    @Autowired
    private DishService dishService;

    /**
     * 保存套餐
     * @param setmealDto
     * @return
     */
    @PostMapping
    @CacheEvict(value = "setmealCache",allEntries = true)//清除setmealCache名称下,所有的缓存数据
    @ApiOperation(value = "新增套餐接口")
    public R save(@RequestBody SetmealDto  setmealDto){
        log.info("保存套餐数据, setmealDto={}",setmealDto.toString());

        setmealService.saveWithDish(setmealDto);

        return R.success();
    }

    @GetMapping("/page")
    @ApiOperation(value = "套餐分页查询接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page",value = "页码",required = true),
            @ApiImplicitParam(name = "pageSize",value = "每页记录数",required = true),
            @ApiImplicitParam(name = "name",value = "套餐名称",required = false),

    })
    public R<Page> page(@RequestParam(required = false, defaultValue = "1") Integer page ,
                        @RequestParam(required = false, defaultValue = "10")Integer pageSize , String name){

        log.info("执行分页查询, 参数 page={}, pageSize={}, name={}",page,pageSize,name);

        //1. 组装分页参数
        Page<Setmeal> pageInfo = new Page<>(page,pageSize);

        //2. 查询排序条件
        LambdaQueryWrapper<Setmeal> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(StringUtils.isNotEmpty(name), Setmeal::getName, name);
        lambdaQueryWrapper.orderByDesc(Setmeal::getUpdateTime);

        //3. 分页查询
        setmealService.page(pageInfo,lambdaQueryWrapper);


        //4. 结果封装完善
        Page<SetmealDto> setmealDtoPage = new Page<>();

        //4.1 赋值total
        setmealDtoPage.setTotal(pageInfo.getTotal());

        //4.2 赋值records ---- List<SetmealDto>
        List<Setmeal> records = pageInfo.getRecords();
        List<SetmealDto> setmealDtoList = records.stream().map(setmeal -> {
            SetmealDto setmealDto = new SetmealDto();
            BeanUtils.copyProperties(setmeal, setmealDto);

            //赋值categoryName
            Category category = categoryService.getById(setmeal.getCategoryId());
            if (category != null) {
                setmealDto.setCategoryName(category.getName());
            }
            return setmealDto;
        }).collect(Collectors.toList());
        setmealDtoPage.setRecords(setmealDtoList);

        //5. 返回结果
        return R.success(setmealDtoPage);
    }


    /**
     * 删除套餐
     * @return
     */
    @DeleteMapping
    @CacheEvict(value = "setmealCache",allEntries = true)//清除setmealCache名称下,所有的缓存数据
    @ApiOperation(value = "删除套餐接口")
    public R delete(@RequestParam List<Long> ids){
        log.info("删除套餐, ids = {}", ids.toString());

        setmealService.removeWithDish(ids);

        return R.success();
    }

    /**
     * 根据分类ID查询套餐列表
     * @param setmeal
     * @return
     */
    @GetMapping("/list")
    @Cacheable(value = "setmealCache",key = "#setmeal.categoryId+'_'+#setmeal.status")
    @ApiOperation(value = "根据分类ID查询套餐列表")
    public R<List<Setmeal>> list(Setmeal setmeal){
        log.info("根据分类ID查询套餐列表, setmeal={}",setmeal.toString());

        //封装查询条件
        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealLambdaQueryWrapper.eq(setmeal.getCategoryId() != null, Setmeal::getCategoryId, setmeal.getCategoryId());
        setmealLambdaQueryWrapper.eq(setmeal.getStatus() != null, Setmeal::getStatus, setmeal.getStatus());
        setmealLambdaQueryWrapper.orderByDesc(Setmeal::getUpdateTime);

        //执行查询
        List<Setmeal> setmealList = setmealService.list(setmealLambdaQueryWrapper);
        return R.success(setmealList);
    }







    //------------------------------------- 实战功能实现 -----------------------------
    @PostMapping("/status/{status}")
    public R<String> updateStatus(@PathVariable Integer status, @RequestParam List<Long> ids){
        //如果是启售套餐 , 需要判定一下是否关联有 停售的菜品
        if(status == 1) {
            LambdaQueryWrapper<SetmealDish> setmealDishLambdaQueryWrapper = new LambdaQueryWrapper<>();
            setmealDishLambdaQueryWrapper.in(SetmealDish::getSetmealId, ids);
            List<SetmealDish> setmealDishList = setmealDishService.list(setmealDishLambdaQueryWrapper);

            if(!CollectionUtils.isEmpty(setmealDishList)){
                List<Long> dishIds = setmealDishList.stream().map(setmealDish -> {
                    return setmealDish.getDishId();
                }).collect(Collectors.toList());

                LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
                dishLambdaQueryWrapper.eq(Dish::getStatus, 0);
                dishLambdaQueryWrapper.in(Dish::getId, dishIds);
                int count = dishService.count(dishLambdaQueryWrapper);
                if(count > 0){
                    throw new CustomException("当前启售的套餐关联有停售的菜品, 无法启售!");
                }

            }
        }

        //查询该批次的套餐数据
        List<Setmeal> setmeals = setmealService.listByIds(ids);
        //更新状态
        setmeals.stream().forEach(setmeal -> {
            setmeal.setStatus(status);
        });
        setmealService.updateBatchById(setmeals);

        return R.success("操作成功");
    }


    /**
     * 根据ID查询套餐数据
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<SetmealDto> getById(@PathVariable Long id){
        log.info("根据ID查询套餐数据, id = {}", id);
        SetmealDto setmealDto = new SetmealDto();

        //获取套餐的基本信息
        Setmeal setmeal = setmealService.getById(id);
        BeanUtils.copyProperties(setmeal, setmealDto);

        //获取套餐关联的菜品列表
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SetmealDish::getSetmealId, id);

        List<SetmealDish> setmealDishList = setmealDishService.list(queryWrapper);

        setmealDto.setSetmealDishes(setmealDishList);

        return R.success(setmealDto);
    }


    /**
     * 修改套餐
     * @param setmealDto
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody SetmealDto setmealDto){
        log.info("接收页面传递的套餐数据, setmealDto= {}",setmealDto);

        setmealService.updateSetmeal(setmealDto);
        return R.success("更新成功");
    }




}
